﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;

namespace AGameOfThrones.board
{
    /// <summary>
    /// Interaction logic for map.xaml
    /// </summary>
    public partial class map : ContentControl
    {
        public const int MAX_NUM_REGIONS = 100;
        public const int MAX_TERRITORY_NAME_LENGTH = 32;

        private List<region> m_regions;
        private byte[] m_greyscaleimage;
        private byte[] m_greyscalepalette;
        
        public map()
        {
           InitializeComponent();    
        }

        public ui.manager UIManager
        {
            get
            {
                try
                {
                    return System.Windows.Application.Current.FindResource("uimanager") as ui.manager;
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine(ex);
                    return null;
                }

            }
        } 

          
        public void InitMap()
        {     
            int width = (int)colorimage.Source.Width;
            int height = (int)colorimage.Source.Height;

            m_greyscaleimage = new byte[width * height];
            m_greyscalepalette = new byte[MAX_NUM_REGIONS];
            m_regions = new List<region>();
                       
            // load greyscale image
            FileStream fs = new FileStream("...\\..\\art\\MapInfo.raw", FileMode.Open);
            fs.Read(m_greyscaleimage, 0, m_greyscaleimage.Length);
            fs.Close();

            // load region info
            TextReader tr = new StreamReader("...\\..\\art\\MapInfo.txt");
            while (tr.Peek() != -1)
            {
                char[] cArrName = new char[MAX_TERRITORY_NAME_LENGTH];
                tr.Read(cArrName, 0, MAX_TERRITORY_NAME_LENGTH);
                string[] strArray = tr.ReadLine().Split(new char[] { ' ' }, 12);

                region r = new region();
                r.m_RegionName = (new String(cArrName)).Trim();
                r.m_RegionID = Int32.Parse(strArray[1]);
                r.m_RegionType = Int32.Parse(strArray[6]);
                r.m_iCenterX = Int32.Parse(strArray[10]);
                r.m_iCenterY = Int32.Parse(strArray[11]);
                r.InitHighlight(m_greyscaleimage, width, height);
                m_greyscalepalette[r.m_RegionID] = (byte)m_regions.Count;
                m_regions.Add(r);
                r.Highlight = false;
                canvas.Children.Add(r);
                UIManager.Panels.Add(r.Panel.Name, r.Panel);
            }
            tr.Close();
        }

        public int GetRegionFromLocation(int X, int Y)
        {
            int width = (int)colorimage.Source.Width;

            int iIndex = (Y * width) + X;

            if (iIndex >= m_greyscaleimage.Length)
            {
                return -1;
            }

            if (m_greyscaleimage[iIndex] == 255)
            {
                iIndex = ((Y - 2) * width) + (X - 2);
            }

            int value = m_greyscaleimage[iIndex];
            return m_greyscalepalette[value];
        }

        private void ContentControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Point p = e.GetPosition((UIElement)sender);
            Console.WriteLine("Pos = " + p);

            int iregion = GetRegionFromLocation((int)p.X, (int)p.Y);
            if (iregion >= 0 && iregion < m_regions.Count)
            {
                foreach (region r in m_regions)
                {
                    r.Highlight = false;
                }

                m_regions[iregion].Highlight = true;
            }

            Console.WriteLine("Region = " + iregion);   
        }

        private void map_control_Drop(object sender, DragEventArgs e)
        {
            Point p = e.GetPosition((UIElement)sender);
            int iregion = GetRegionFromLocation((int)p.X, (int)p.Y);
            if (iregion >= 0 && iregion < m_regions.Count)
            {
                foreach (region r in m_regions)
                {
                    r.Highlight = false;
                }

                m_regions[iregion].Highlight = true;
            }

            if (e.Data.GetDataPresent(typeof(piece.piece)))
            {
                network.client c = FindResource("client") as network.client;
                if (c != null)
                {             
                    piece.piece uipiece = e.Data.GetData(typeof(piece.piece)) as piece.piece;
                    game.piece gamepiece = uipiece.DataContext as game.piece;
                    Point rel = e.GetPosition(m_regions[iregion].Panel);

                    messages.request_movepiece message = new messages.request_movepiece();
                    message.PieceName = gamepiece.PieceName;
                    message.OldPosition.Panel = (uipiece.Parent as Panel).Name;
                    message.OldPosition.X = uipiece.Margin.Left;
                    message.OldPosition.Y = uipiece.Margin.Top;
                    message.NewPosition.Panel = m_regions[iregion].Panel.Name;
                    message.NewPosition.X = rel.X - uipiece.DragStart.X;
                    message.NewPosition.Y = rel.Y - uipiece.DragStart.Y;                                     
                    c.SendMessage(message);
                }

                /*
                parent.Children.Remove(piece);
                m_regions[iregion].Panel.Children.Add(piece);
                piece.Margin = new Thickness(, rel.Y - piece.DragStart.Y, 0, 0);
                gamepiece.Position.X = piece.Margin.Left;
                gamepiece.Position.Y = piece.Margin.Top;
                gamepiece.Position.Panel = m_regions[iregion].m_RegionName;
                 * */
            }


            Console.WriteLine("Drop Region = " + iregion);   

        }

        private void map_control_DragOver(object sender, DragEventArgs e)
        {
            Point p = e.GetPosition((UIElement)sender);
            int iregion = GetRegionFromLocation((int)p.X, (int)p.Y);
            if (iregion >= 0 && iregion < m_regions.Count)
            {
                foreach (region r in m_regions)
                {
                    r.Highlight = false;
                }

                m_regions[iregion].Highlight = true;
            }
        }
    }
}
